package com.coai.ai.service

import com.coai.ai.model.*
import com.theokanning.openai.completion.chat.ChatMessage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.stereotype.Service
import java.time.LocalDateTime

/**
 * 智能客服引擎
 */
@Service
class CustomerServiceEngine(
    private val openAIService: OpenAIService,
    private val mongoTemplate: MongoTemplate
) {
    
    /**
     * 处理客户咨询
     */
    suspend fun handleCustomerQuery(
        customerId: String,
        query: String,
        conversationId: String,
        context: Map<String, Any>? = null
    ): CustomerServiceResponse = withContext(Dispatchers.IO) {
        
        // 1. 识别意图
        val intent = recognizeIntent(query)
        
        // 2. 情绪分析
        val sentiment = openAIService.analyzeSentiment(query)
        
        // 3. 获取客户画像
        val profile = getOrCreateCustomerProfile(customerId)
        
        // 4. 更新客户画像
        updateCustomerProfile(profile, sentiment, query)
        
        // 5. 搜索知识库
        val knowledgeResults = searchKnowledgeBase(query)
        
        // 6. 获取对话历史
        val history = getConversationHistory(conversationId)
        
        // 7. 构建提示词
        val systemPrompt = buildSystemPrompt(profile, knowledgeResults, context)
        val messages = buildMessages(systemPrompt, history, query)
        
        // 8. 生成回复
        val response = openAIService.chatCompletion(messages)
        
        // 9. 保存对话历史
        saveConversationHistory(conversationId, customerId, query, response)
        
        // 10. 返回结果
        CustomerServiceResponse(
            message = response,
            intent = intent,
            sentiment = sentiment,
            confidence = 0.9,
            suggestedActions = generateSuggestedActions(intent, sentiment),
            knowledgeReferences = knowledgeResults.map { it.id!! }
        )
    }
    
    /**
     * 识别用户意图
     */
    private suspend fun recognizeIntent(query: String): String {
        val intents = listOf(
            "产品咨询",
            "价格询问",
            "技术支持",
            "投诉建议",
            "购买下单",
            "退换货",
            "账户问题",
            "其他"
        )
        
        return openAIService.classifyText(query, intents)
    }
    
    /**
     * 搜索知识库
     */
    private suspend fun searchKnowledgeBase(
        query: String,
        limit: Int = 5
    ): List<KnowledgeEntry> {
        
        // 简单的关键词匹配（实际应使用向量相似度搜索）
        val keywords = openAIService.extractKeywords(query, 3)
        
        val criteria = Criteria().orOperator(
            keywords.map { keyword ->
                Criteria.where("question").regex(keyword, "i")
            }
        )
        
        val query = Query(criteria).limit(limit)
        return mongoTemplate.find(query, KnowledgeEntry::class.java)
    }
    
    /**
     * 获取或创建客户画像
     */
    private fun getOrCreateCustomerProfile(customerId: String): CustomerProfile {
        val query = Query(Criteria.where("customerId").`is`(customerId))
        return mongoTemplate.findOne(query, CustomerProfile::class.java)
            ?: CustomerProfile(customerId = customerId).also {
                mongoTemplate.save(it)
            }
    }
    
    /**
     * 更新客户画像
     */
    private fun updateCustomerProfile(
        profile: CustomerProfile,
        sentiment: SentimentResult,
        query: String
    ) {
        val updated = profile.copy(
            interactionCount = profile.interactionCount + 1,
            lastInteractionAt = LocalDateTime.now(),
            sentimentHistory = profile.sentimentHistory + SentimentRecord(
                score = sentiment.score,
                text = query
            ),
            updatedAt = LocalDateTime.now()
        )
        
        mongoTemplate.save(updated)
    }
    
    /**
     * 获取对话历史
     */
    private fun getConversationHistory(conversationId: String): ConversationHistory {
        val query = Query(Criteria.where("conversationId").`is`(conversationId))
        return mongoTemplate.findOne(query, ConversationHistory::class.java)
            ?: ConversationHistory(conversationId = conversationId)
    }
    
    /**
     * 保存对话历史
     */
    private fun saveConversationHistory(
        conversationId: String,
        userId: String,
        userMessage: String,
        aiResponse: String
    ) {
        val history = getConversationHistory(conversationId)
        
        history.messages.add(ChatMessage(MessageRole.USER, userMessage))
        history.messages.add(ChatMessage(MessageRole.ASSISTANT, aiResponse))
        history.updatedAt = LocalDateTime.now()
        
        mongoTemplate.save(history)
    }
    
    /**
     * 构建系统提示词
     */
    private fun buildSystemPrompt(
        profile: CustomerProfile,
        knowledgeResults: List<KnowledgeEntry>,
        context: Map<String, Any>?
    ): String {
        return """
            你是一名专业的客服助手，负责帮助客户解决问题。
            
            客户信息：
            - 客户ID: ${profile.customerId}
            - 公司: ${profile.company ?: "未知"}
            - 行业: ${profile.industry ?: "未知"}
            - 历史互动次数: ${profile.interactionCount}
            
            相关知识：
            ${knowledgeResults.joinToString("\n") { "- ${it.question}: ${it.answer}" }}
            
            请遵循以下原则：
            1. 友好、专业、耐心
            2. 准确理解客户需求
            3. 提供清晰的解决方案
            4. 必要时主动询问补充信息
            5. 如果无法解决，建议转人工客服
        """.trimIndent()
    }
    
    /**
     * 构建消息列表
     */
    private fun buildMessages(
        systemPrompt: String,
        history: ConversationHistory,
        currentQuery: String
    ): List<ChatMessage> {
        val messages = mutableListOf<ChatMessage>()
        
        // 系统提示
        messages.add(ChatMessage("system", systemPrompt))
        
        // 历史消息（最近10条）
        history.messages.takeLast(10).forEach { msg ->
            messages.add(ChatMessage(msg.role.name.lowercase(), msg.content))
        }
        
        // 当前查询
        messages.add(ChatMessage("user", currentQuery))
        
        return messages
    }
    
    /**
     * 生成建议操作
     */
    private fun generateSuggestedActions(
        intent: String,
        sentiment: SentimentResult
    ): List<String> {
        val actions = mutableListOf<String>()
        
        when (intent) {
            "产品咨询" -> actions.add("发送产品详情")
            "价格询问" -> actions.add("发送报价单")
            "技术支持" -> actions.add("安排技术人员跟进")
            "投诉建议" -> {
                actions.add("升级给主管")
                if (sentiment.score < -0.5) {
                    actions.add("紧急处理")
                }
            }
            "购买下单" -> actions.add("引导下单流程")
        }
        
        return actions
    }
}

/**
 * 客服响应
 */
data class CustomerServiceResponse(
    val message: String,
    val intent: String,
    val sentiment: SentimentResult,
    val confidence: Double,
    val suggestedActions: List<String>,
    val knowledgeReferences: List<String>
)
